import SparkMD5 from "spark-md5";

/**
 * 读取文件流中的二进制流
 * @param file
 */
const _readArrayBuffer = (file: File): Promise<ArrayBuffer> => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = e => {
            // @ts-ignore
            let result: ArrayBuffer = e.target?.result;
            resolve(result);
        }
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
    })
}

/** 将字符串转换为二进制流 */
const _str2ArrayBufferConv = (content: string): ArrayBuffer => new TextEncoder().encode(content).buffer;

/**
 * 计算文件的 MD5
 * @param file
 */
export const computedMd5ByFile = async (file: File) => {
    const bytes = await _readArrayBuffer(file);
    return SparkMD5.ArrayBuffer.hash(bytes);
}

/**
 * 计算字符串的 MD5
 * @param content
 */
export const computedMd5ByStr = (content: string) => {
    // 稍作修改：使用 FileReader 获取文件内容 \r\n 换行，这里没有，所以强行加上
    content = content.replace(/\n/g, '\r\n');
    const bytes = _str2ArrayBufferConv(content);
    return SparkMD5.ArrayBuffer.hash(bytes);
}

